package org.batatasframework.support.searchable.writer;

import java.util.List;

import org.batatasframework.support.searchable.ResultHeadInfo;
import org.batatasframework.support.searchable.SearchableInputStream;
import org.batatasframework.support.searchable.result.ResultRow;


public class HtmlResultWriter extends AbstractResultWriter{
	
	public HtmlResultWriter(SearchableInputStream inputStream) throws Exception {
		super(inputStream);
	}

	private final StringBuffer html = new StringBuffer();
	
	private StringBuffer line;
	
	private int lineNumbers;
	
	@Override
	protected void renderHead(ResultHeadInfo[][] heads) {
		html.append("<thead>");
		for(ResultHeadInfo[] li : heads){
			html.append("<tr>");
			for(ResultHeadInfo hi : li){
				html.append("<td");
				if(hi.getColspan() > 1) html.append(" colspan='").append(hi.getColspan()).append("'");
				if(hi.getRowspan() > 1) html.append(" rowspan='").append(hi.getRowspan()).append("'");
				
				html.append(">").append(hi.getTitle()).append("</td>");
			}
			html.append("</tr>");
		}
		html.append("</thead>");
	}
	
	private void appendToHtml(){
		if(null != line){
			html.append("<tr>").append(line).append("</tr>");
			line = null;
		}
	}
	
	@Override
	public void newLine() {
		appendToHtml();
		lineNumbers++;
		line = new StringBuffer("<td>").append(lineNumbers).append("</td>");
	}
	
	@Override
	public void group(Object value, int size) {
		appendToHtml();
		html.append("<td></td><td colspan='").append(inputStream.getColumnSize())
			.append("'>").append(value)
			.append("<font color='blue' size='12'>").append(size)
			.append("</font></td>");
	}
	
	@Override
	public void append(Object value) {
		line.append("<td>").append(value).append("</td>");
	}
	
	@Override
	public void renderBody(List<? extends ResultRow> rows) throws Exception {
		super.renderBody(rows);
		appendToHtml();
	}
	
	public String getHtml() {
		return html.toString();
	}
}
